package com.lw.leetcode.str.a;

/**
 * 415. 字符串相加
 *
 * @Author liw
 * @Date 2021/5/8 15:33
 * @Version 1.0
 */
public class AddStrings {

    public static void main(String[] args) {
        AddStrings test = new AddStrings();
        String s = test.addStrings("9999", "91");
        System.out.println(s);
    }

    public String addStrings(String num1, String num2) {
        if (num1 == null) {
            return num2;
        }
        if (num2 == null) {
            return num1;
        }
        int l1 = num1.length();
        int l2 = num2.length();
        StringBuilder str;
        if (l1 > l2) {
            l2 = l1;
            l1 = num2.length();
            str = new StringBuilder(num1);
            num1 = num2;
            num2 = str.toString();
        }

        num1 = new StringBuilder(num1).reverse().toString();
        num2 = new StringBuilder(num2).reverse().toString();

        str = new StringBuilder();
        int k = 0;
        for (int i = 0; i < l1; i++) {
            int c1 = num1.charAt(i) - 48;
            int c2 = num2.charAt(i) - 48;
            int c = c1 + c2 + k;
            if (c > 9) {
               k = 1;
               c = c - 10;
            } else {
                k = 0;
            }
            str.append(c);
        }
        for (int i = l1; i < l2; i++) {
            int c2 = num2.charAt(i) - 48;
            int c = c2 + k;
            if (c > 9) {
                k = 1;
                c = c - 10;
                str.append(c);
            } else {
                str.append(c);
                k = 0;
                if (i + 1 < l2) {
                    str.append(num2.substring(i + 1));
                    break;
                }
            }
        }
        if (k == 1) {
            str.append('1');
        }
        return str.reverse().toString();
    }
}
